<?php
/**
 * 客诉模型
 * (model)
 */
namespace App\Models\Quality;

use App\Models\Basics\SysCountry;
use App\Models\Basics\SysArea;
use App\Models\Product\ProductSku;
use App\Models\Product\ProductClassify;
use Illuminate\Database\Eloquent\Model;
class QComplaint extends Model
{
    protected $table = 'quality_complaint';

    protected $guarded = [];

    protected $casts = [
        'tag' => 'array',
    ];

    //渠道来源
    public static $_origin = [
        1 => 'Email',
        2 => 'Review',
        3 => 'Feedback',
        4 => '社媒',
        9 => '其他',
    ];

    //状态
    public static $_status = [
        0 => '未统计',
        1 => '已统计',
    ];

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function country(){
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public function classify(){
        return $this->belongsTo(ProductClassify::class,'classify_id');
    }

    //默认基于当前模型名(QComplaint)来决定外键名称：模型名_id
    public function image(){
        return $this->hasOne(QComplaintImage::class,'complaint_id');
    }

    public static function getData($re){
        foreach ($re as $row){
            $temp1 = [
                $row->report_date,
                $row->area->area ?? '',
                $row->country->country ?? '',
                self::$_origin[$row->origin],
                $row->order_no,
                $row->sku->psku_code ?? '',
                $row->sku->psku_cn ?? '',
                $row->classify->title ?? '',
                $row->seller_sku,
            ];
            $temp2 = [];
            foreach (QDictTag::$_type as $type){
                $temp2['type-'.$type] = '';
            }
            if(!is_null($row->tag)){
                $tagOption = QDictTag::getTagOption($row->tag);
                foreach (QDictTag::$_type as $typeId => $type){
                    if(array_key_exists($typeId,$row->tag)){
                        $str = [];
                        foreach ($row->tag[$typeId] as $tag){
                            $str[$tag] = array_key_exists($tag,$tagOption) ? $tagOption[$tag] : '';
                        }
                        if(!empty($str)){
                            $temp2['type-'.$type] = implode(',',$str);
                        }
                    }
                }
            }
            $temp3 = [
                'content' => $row->content,
            ];
            yield $temp1 + $temp2 + $temp3;
        }
    }
}
